package com.ming_za.odupdaterserver.core.interceptor;

import com.ming_za.odupdaterserver.core.config.ConfigManager;
import com.ming_za.odupdaterserver.core.config.type.BooleanValue;
import com.ming_za.odupdaterserver.core.exception.BusinessException;
import com.ming_za.odupdaterserver.core.exception.ROEnum;
import com.ming_za.odupdaterserver.core.utils.NetworkUtils;
import com.ming_za.odupdaterserver.core.utils.account.AccountManager;
import com.ming_za.odupdaterserver.core.utils.account.param.ReturnAccountPackage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AdminVerificationInterceptor implements HandlerInterceptor {

    private boolean enableVerification;
    private final AccountManager accountManager;

    public AdminVerificationInterceptor(ConfigManager configManager, AccountManager accountManager) {
        this.accountManager = accountManager;

        BooleanValue loginVerification = configManager.getLoginVerification();
        this.enableVerification = loginVerification.getValue();
        loginVerification.bindListener((v)->{
            this.enableVerification = v;
        });

        if (this.enableVerification && accountManager.getAllAccount().isEmpty()){
            loginVerification.saveValue(false);
        }

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

        if (request.getMethod().equals("OPTIONS")){
            return false;
        }

        if (enableVerification){
            //需要验证
            String token = request.getHeader("token");

            String newToken;

            ReturnAccountPackage<String> token1 = accountManager.checkToken(0, token, request.getRemoteHost(), 0);

            if (!token1.isSuccess()){
                throw new BusinessException(ROEnum.USER_TOKEN_FAILURE);
            }

            newToken = token1.getData();
            response.addHeader("token", newToken);

            if (newToken != null){
                response.setHeader("token",newToken);
            }
        }else if (NetworkUtils.notLocalHost(request.getRemoteHost())){
            throw new BusinessException(ROEnum.USER_REMOTE_LOGIN_ERROR);
        }
        return true;
    }
}
